/*
 * @Author: 姚潘涛
 * @Date: 2024-04-08 20:36:40
 * @LastEditors: 姚潘涛
 * @LastEditTime: 2024-05-23 18:33:48
 * @FilePath:
 * /xict_ws/src/xcmg-intelligent-cockpit-three/src/xict_ui/src/xict_ui_core/paintitem.cpp
 * @Description:
 *
 * Copyright (c) 2024 by pandaman, All Rights Reserved.
 */
#include "xict_ui_core/paintitem.h"
#include <QDateTime>

PaintItem::PaintItem(QQuickItem* parent) : QQuickItem(parent) {
    // 这句不加会报错
    setFlag(ItemHasContents, true);
    settop_screen(false);
    setcut_num(1);
    // 默认图片
    //     m_image = QImage();
    m_image = QImage(10, 10, QImage::Format_RGB888);
    m_image.fill(QColor(Qt::black));
}

void PaintItem::updateImage(const QImage& img, int state) {
    //    m_image = img;
    if (m_cut_num > 1) {
        if (state == -1) {
            int sub_width = img.width() / m_cut_num;
            if (m_top_screen) {   // 显示开机动画
                m_image = img.copy((img.width() - 1920) / 2, 0, 1920, 1080);
            } else {
                m_image = img.copy(m_image_index * sub_width + 1, 1080,
                                   sub_width - 1, 1920);
            }
        } else {
            if (m_top_screen) {
                m_image = img.copy();
            } else if (state > 0) {
                int sub_width = img.width() / m_cut_num;
                m_image =
                    img.copy(m_image_index * sub_width + 10, 0, sub_width - 10,
                             img.height());   // 显示实时图像
            } else {
                int sub_width = img.width() / 3;
                if (m_image_index > 0 && m_image_index < 4) {
                    m_image = img.copy((m_image_index - 1) * sub_width + 10, 0,
                                       sub_width - 10,
                                       img.height());   // 显示实时图像
                } else
                    m_image = QImage();
            }
        }
    } else {
        if (m_revolve) {
            QMatrix matrix;
            if (state == 1) {
                matrix.rotate(90.0);
            } else {
                matrix.rotate(-90.0);
            }
            QImage tmp_img = img.transformed(matrix);
            m_image        = tmp_img.copy();
        } else {
            m_image = img.copy();
        }
    }
    update();
}

QSGNode* PaintItem::updatePaintNode(QSGNode* oldNode,
                                    QQuickItem::UpdatePaintNodeData*) {
    auto node = dynamic_cast<QSGSimpleTextureNode*>(oldNode);

    if (!node) {
        node = new QSGSimpleTextureNode();
    }

    QSGTexture* m_texture = window()->createTextureFromImage(
        m_image, QQuickWindow::TextureIsOpaque);
    node->setOwnsTexture(true);
    node->setRect(boundingRect());
    node->markDirty(QSGNode::DirtyForceUpdate);
    node->setTexture(m_texture);
    return node;
}
